package com.tansun.easycare.rule.deployonline.web;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tansun.easycare.rule.monitor.entity.RuleMonitorInfo;
import com.tansun.easycare.rule.monitor.service.RuleMonitorInfoService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.DeferredFileOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.config.Global;
import com.tansun.easycare.core.utils.ResponseTable;
import com.tansun.easycare.rule.common.JsonMessage;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.common.model.SelectEditorVo;
import com.tansun.easycare.rule.datacomponent.entity.RuleDatacomponent;
import com.tansun.easycare.rule.datacomponent.service.IDataComponentService;
import com.tansun.easycare.rule.datasource.service.RuleDatasourceService;
import com.tansun.easycare.rule.deployonline.entity.ReflactData;
import com.tansun.easycare.rule.deployonline.entity.RuleDataInfo;
import com.tansun.easycare.rule.deployonline.entity.RuleDeployment;
import com.tansun.easycare.rule.deployonline.model.DeployInfo;
import com.tansun.easycare.rule.deployonline.model.ReflactDataVO;
import com.tansun.easycare.rule.deployonline.model.RuleDeployVO;
import com.tansun.easycare.rule.deployonline.service.ReflactDataService;
import com.tansun.easycare.rule.deployonline.service.RuleDeployOnlineService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.front.entity.RuleDatasource;
import com.tansun.easycare.rule.ruleflow.service.RuleFlowService;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.sparkCode.config.DeployStatus;
import com.tansun.rule.utils.HttpUtils;
import com.tansun.rule.utils.LoggerManager;
import com.tansun.workflow.api.IWorkflowService;
import com.tansun.workflow.model.ProcessBean;
import com.tansun.workflow.model.ProcessInfo;
import com.tansun.workflow.model.TaskBean;

/**
 * 规则发布
 *
 * @author lixs
 */
@RestController
@RequestMapping(value = "/ruleProj/deployOnline")
public class RuleDeployOnlineController extends RuleBaseController {

    @Autowired
    private RuleDeployOnlineService ruleDeployOnlineService;
//    @Autowired
    private RuleFlowService ruleFlowService;

    @Autowired
    private IDataComponentService dataComponentService;

    @Autowired
    private ReflactDataService reflactDataService;
	@Autowired
	private RuleDatasourceService datasourceService;
    /**
     * 部署任务页面
     *
     * @param request HttpServletRequest
     * @param map     ModelMap
     * @return JSP路径
     */

    @RequestMapping("index")
    public ResponseTable<RuleDeployment> index(@RequestBody RuleManageVO param) throws Exception {
        RuleDeployment ruleDeployment = new RuleDeployment();
        ruleDeployment.setProjectCode(param.getProjectCode());
        PageInfo<RuleDeployment> page = this.ruleDeployOnlineService.findPage(new Page<RuleDeployment>(), ruleDeployment);
        ResponseTable<RuleDeployment>  res = new ResponseTable<>(page);
        return res;
    }
    
    @RequestMapping("detailInfo")
    @ResponseBody
    public RuleDeployVO detailInfo(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws Exception {
        RuleDeployVO ruleDeployVO = null;
            ruleDeployVO = this.ruleDeployOnlineService.findRuleDeploy("84af65b4fcdc45cbb2069fddb88fc407");
        return ruleDeployVO;
    }
    
    /**
     * 新建部署页面
     *
     * @param request HttpServletRequest
     * @param map     ModelMap
     * @return JSP路径
     */
    @RequestMapping("deployNewPage")
    public ResponseVO deployNewPage(@RequestBody DeployInfo deployInfo) throws Exception {

    	ResponseVO  res  = new  ResponseVO();
        RuleVersioninfo info = new RuleVersioninfo();
        info.setProjectCode(deployInfo.getProjectCode());
        //info.setModelType(RuleModelTypeEnum.StrategyFlow.code);
        info.setModelType(RuleModelTypeEnum.RuleFlow.code);//不选择决策流

       // List<SelectEditorVo> list = ruleFlowService.getAllNewPublishVersion(info);
        //map.put("list", list);
        String  operType = deployInfo.getOperType();
        String  id = deployInfo.getId();
        RuleDeployVO ruleDeployVO = null;
        if ("add".equals(operType)) {
            ruleDeployVO = new RuleDeployVO();
            ruleDeployVO.setRuleDeployment(new RuleDeployment());
        } else {
            ruleDeployVO = this.ruleDeployOnlineService.findRuleDeploy(id);

        }
        String deployInd = Global.getConfig("Deploy.jar.ind");
        if (deployInd != null && "0".equals(deployInd)) {
            if (!"display".equals(operType)) {
                operType = "dataOperType";
            }
        }
        ruleDeployVO.setRuleDatasources(datasourceService.findList(new RuleDatasource()));
        res.setData(ruleDeployVO);
        return res;

    }

    /**
     * 新建部署
     *
     * @param request HttpServletRequest
     * @param map     ModelMap
     * @return 新建结果信息
     */
    @RequestMapping("deployNewAction")
    public ResponseVO deployNewAction(HttpServletRequest request, @RequestBody RuleDeployVO ruleDeploy) throws Exception {
    	ResponseVO res = new ResponseVO();
        try {
            this.ruleDeployOnlineService.saveOrUpdate(ruleDeploy);
        } catch (BizException e) {
           res.setStatus(ResponseVO.ERROR);
           res.setDescription(e.getMessage());
        }
        return res;
    }

    /**
     * 删除 逻辑删除，修改状态为0
     *
     * @param request HttpServletRequest
     * @param map     ModelMap
     * @param code    部署任务的代码
     * @return 删除结果信息
     */
    @RequestMapping("delDeploy")
    public ResponseVO
     delDeploy(HttpServletRequest request,@RequestBody RuleDeployment ruleDeploy ) throws Exception {
        if (StringUtils.isEmpty(ruleDeploy.getId())) {
            throw new BizException("");
        }
        this.ruleDeployOnlineService.deleteRuleDeploy(ruleDeploy.getId());
        return  new ResponseVO();
    }

    @RequestMapping("doRulePackage")
    public ResponseVO
     doRulePackage(@RequestBody RuleDeployment ruleDeploy ) throws Exception {
    	ResponseVO res = new ResponseVO();
        try {
            this.ruleDeployOnlineService.createRulePackage(ruleDeploy.getId(), ruleDeploy.getCurrUserNum(), this.getCurrProjectCode());
        } catch (Exception e) {
            res.setStatus(ResponseVO.ERROR);
        }
        return res;
    }

    /**
     * 规则Drl包下载
     *
     * @param request     HttpServletRequest
     * @param map         ModelMap
     * @param code        部署任务的代码
     * @param fileIsExsit 文件是否存在
     */
    @RequestMapping("downLoadPackage")
    public void downLoadPackage(@RequestParam("projectCode") String  projectCode, HttpServletResponse response,@RequestParam("code") String code, @RequestParam("fileIsExsit") String fileIsExsit) throws Exception {
        String currProjectCode = projectCode;

        String path = Global.getConfig("DeployFileDir") + "/" + currProjectCode + "/deployOnline/" + code + "/rulePackage.jar";
        File file = new File(path);

        if ("fileIsExsit".equals(fileIsExsit)) {
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();// OutputStream();
            if (!file.exists()) {
                pw.write(JSON.toJSONString(new ResMessage("faulte", "文件不存在！")));
            } else {
                pw.write(JSON.toJSONString(new ResMessage("success", "文件存在！")));
            }
            pw.flush();
            return;

        }

        OutputStream os = response.getOutputStream();
        try {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=rulePackage.jar");
            response.setContentType("application/octet-stream; charset=utf-8");
            os.write(FileUtils.readFileToByteArray(new File(path)));
            os.flush();
        } finally {
            if (os != null) {
                os.close();
            }
        }


    }
    /**
     * 规则Jar包下载
     *
     * @param request     HttpServletRequest
     * @param map         ModelMap
     * @param code        部署任务的代码
     * @param fileIsExsit 文件是否存在
     */
    @RequestMapping("downloadJarPackage")
    public void downloadJarPackage(@RequestParam("projectCode") String  projectCode, HttpServletResponse response,@RequestParam("code") String code, @RequestParam("fileIsExsit") String fileIsExsit) throws Exception {
        String currProjectCode = projectCode;

        String path = Global.getConfig("DeployFileDir") + "/" + currProjectCode + "/deployOnline/" + code + "/ruleSparkPackage.jar";
        File file = new File(path);

        if ("fileIsExsit".equals(fileIsExsit)) {
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();// OutputStream();
            if (!file.exists()) {
                pw.write(JSON.toJSONString(new ResMessage("faulte", "文件不存在！")));
            } else {
                pw.write(JSON.toJSONString(new ResMessage("success", "文件存在！")));
            }
            pw.flush();
            return;

        }

        OutputStream os = response.getOutputStream();
        try {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=ruleSparkPackage.jar");
            response.setContentType("application/octet-stream; charset=utf-8");
            os.write(FileUtils.readFileToByteArray(new File(path)));
            os.flush();
        } finally {
            if (os != null) {
                os.close();
            }
        }


    }

    /**
     * 查看包日志
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param map      ModelMap
     * @param code     部署任务的代码
     * @return JSP路径
     */
    @RequestMapping("showPackageLog")
    public String showPackageLog(HttpServletRequest request, HttpServletResponse response, String code, ModelMap map) throws Exception {
        String currProjectCode = this.getCurrProjectCode();
        String path = Global.getConfig("DeployFileDir") + "/" + currProjectCode + "/deployOnline/" + code + "/packageLog.log";
        File logf = new File(path);
        if (logf.exists()) {
            String log = FileUtils.readFileToString(logf, "UTF-8");
            map.put("pakLog", log);
        }
        return "rule/deployonline/pakLog";
    }

    /**
     * 查看历史包信息
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param map      ModelMap
     * @param code     部署任务的代码
     * @return JSP路径
     */
    @RequestMapping("showHisPackage")
    public String showHisPackage(HttpServletRequest request, HttpServletResponse response, String code, ModelMap map) throws Exception {
        String currProjectCode = this.getCurrProjectCode();
        String path = Global.getConfig("DeployFileDir") + "/" + currProjectCode + "/deployOnline/" + code;
        File dir = new File(path);
        List<String> dirNames = new ArrayList<String>();
        SimpleDateFormat spf = new SimpleDateFormat("yyyyMMddHHmmss");
        for (File file : dir.listFiles()) {
            if (file.getName().startsWith("_") && file.isDirectory()) {
                long pakmodifylong = new File(path + "/" + file.getName() + "/rulePackage.jar").lastModified();
                dirNames.add(spf.format(new Date(pakmodifylong)) + file.getName());


            }
        }
        Collections.reverse(dirNames);
        map.put("dirNames", dirNames);
        map.put("code", code);
        return "rule/deployonline/hisPak";
    }

    @RequestMapping("reflactDialog")
    public String reflactDialog(HttpServletRequest request, String projectCode, String modelName, String id, ModelMap map) throws Exception {
        if(StringUtils.isNoneEmpty(projectCode)){
        	projectCode = this.getCurrProjectCode();
        }
        RuleDeployment deployment = this.ruleDeployOnlineService.deployRemoteServer(id, projectCode);
    	map.put("deployment", deployment);
        map.put("modelName", modelName);
        map.put("enterPoints", deployment.getEnterPoints().split(";"));
        map.put("id", id);
        return "/rule/deployonline/reflactDialog";
    }
    /**
     * 部署规则包到执行服务器
     *
     * @param request HttpServletRequest
     * @param map     ModelMap
     * @param code    部署任务的代码
     * @return 部署结果信息
     */
    @RequestMapping("doDeploySpark")
    public @ResponseBody ResponseVO doDeploySpark(HttpServletRequest request, String id, ModelMap map) throws Exception {
    	ResponseVO responseVO = new ResponseVO();
    	RuleDeployment deployment = null;
    	try {
			deployment = this.ruleDeployOnlineService.deployRemoteServer(id, this.getCurrProjectCode());
			String result = this.ruleDeployOnlineService.runRemoteDeploy(deployment);
	    	ReflactData reflactData = new ReflactData();
	    	reflactData.setDeployId(deployment.getId());
	    	reflactData.setEnterPonit(deployment.getEnterPoints());
	    	reflactData.setProjectCode(deployment.getProjectCode());
	    	List<ReflactData> reflactDataList = this.reflactDataService.findList(reflactData);
	    	ReflactDataVO reflactDataVO = new ReflactDataVO();
	    	reflactDataVO.setDeploymentId(deployment.getId());
	    	reflactDataVO.setEnterPoint(deployment.getEnterPoints());
	    	reflactDataVO.setProjectCode(deployment.getProjectCode());
	    	reflactDataVO.setReflactDataList(reflactDataList);
	    	this.ruleDeployOnlineService.setReflactData(deployment,reflactDataVO);
	    	JSONObject json = JSON.parseObject(result);
            if (json!=null && "success".equalsIgnoreCase(json.getString("code"))) {
				deployment.setStatusInd(DeployStatus.DEPLOY_NOT_CALC);
				deployment.setCalcStatus(DeployStatus.DEPLOY_NOT_CALC);
				this.ruleDeployOnlineService.save(deployment);
				responseVO.setStatus(ResponseVO.OK);
            	responseVO.setDescription("规则包已经部署成功！");
            } else {
				deployment.setStatusInd(DeployStatus.NOT_DEPLOY);
				deployment.setCalcStatus(DeployStatus.NOT_DEPLOY);
				this.ruleDeployOnlineService.save(deployment);
            	responseVO.setStatus(ResponseVO.ERROR);
            	responseVO.setDescription(json.getString("msg"));
            	responseVO.setDesDetail(json.getString("msg"));
            }
		} catch (Exception e) {
			if(deployment!=null) {
				deployment.setStatusInd(DeployStatus.NOT_DEPLOY);
				deployment.setCalcStatus(DeployStatus.NOT_DEPLOY);
				this.ruleDeployOnlineService.save(deployment);
			}
			log.error("联机部署失败", e);
            responseVO.setStatus(ResponseVO.ERROR);
        	Throwable root = ExceptionUtils.getRootCause(e);
			if( root==null ) {
				root = e;
			}
            responseVO.setDescription("联机部署失败：" + root.getMessage());
            String desDetail = com.tansun.easycare.core.utils.StringUtils.toHtml(ExceptionUtils.getStackTrace(e));
            responseVO.setDesDetail(desDetail);
		}
    	return responseVO;
    }
    /**
     * 部署规则包到执行服务器
     *
     * @param request HttpServletRequest
     * @param map     ModelMap
     * @param code    部署任务的代码
     * @return 部署结果信息
     */
    @RequestMapping("doDeploy")
    public ResponseVO doDeploy(HttpServletRequest request,@RequestBody RuleDeployment ruleDeploy) {
    	ResponseVO responseVO = new ResponseVO();
        try {
        	System.out.println(Global.getConfig("RuleDeploy"));
            RuleDeployment deployment = this.ruleDeployOnlineService.deployRemoteServer(ruleDeploy.getId(),ruleDeploy.getProjectCode());
            this.ruleDeployOnlineService.synchExeTable(ruleDeploy.getId(),deployment.getProjectCode());
            String result = HttpUtils.deployRuleDataPackage(deployment.getServerUrl()+ Global.getConfig("RuleDeploy"),
										            		deployment.getEnterPoints(),
										                    deployment.getUserName(),
										                    deployment.getPassword(),
										                    "", 
										                    deployment.getProjectCode());
            com.tansun.ruledata.common.ResponseVO resp = JSON.parseObject(result,com.tansun.ruledata.common.ResponseVO.class);
            if (resp.getStatus() == com.tansun.ruledata.common.ResponseVO.SUCCESS) {
            	responseVO.setStatus(ResponseVO.OK);
            	responseVO.setDescription("规则包已经部署成功！");
            } else {
            	responseVO.setStatus(ResponseVO.ERROR);
            	String expHTML = com.tansun.easycare.core.utils.StringUtils.toHtml(resp.getDesDetail());
            	responseVO.setDescription((String)resp.getReturnData());
            	responseVO.setDesDetail(expHTML);
            }
        } catch (Exception e) {
            log.error("联机部署失败", e);
            responseVO.setStatus(ResponseVO.ERROR);
        	Throwable root = ExceptionUtils.getRootCause(e);
			if( root==null ) {
				root = e;
			}
            responseVO.setDescription("联机部署失败：" + root.getMessage());
            String desDetail = com.tansun.easycare.core.utils.StringUtils.toHtml(ExceptionUtils.getStackTrace(e));
            responseVO.setDesDetail(desDetail);
        }
        return responseVO;
//    	RuleDataInfo ruleDataInfo = this.ruleDeployOnlineService.getRulePackageData(this.getCurrProjectCode(), id);
//    	String result = HttpUtils.deployRuleDataPackage(ruleDataInfo.getDeployment().getServerUrl(),this.getCurrProjectCode(),JSON.toJSONString(ruleDataInfo));
//        JsonMessage ret = JSON.parseObject(result,JsonMessage.class);
//        if (ret.getResult()) {
//            return new ResMessage("success", "规则包已经部署成功！");
//        } else {
//            return new ResMessage("falut", result);
//        }
    }
    /**
     * 上传数据到服务器
     * @param file
     * @param res
     * @param projectCode
     * @param id
     * @throws Exception
     */
    @RequestMapping("upload")
    public void upload(@RequestParam("file") MultipartFile file, HttpServletResponse res, String projectCode, String id) throws Exception {
        // MultipartFile对象转换
    	RuleDeployment deployment = this.ruleDeployOnlineService.deployRemoteServer(id, this.getCurrProjectCode());
    	String url = deployment.getServerUrl()+Global.getConfig("RuleDataUpload");
		
		MultipartEntityBuilder entity=MultipartEntityBuilder.create();
        CommonsMultipartFile multipartFile = (CommonsMultipartFile)file;
		DiskFileItem diskFileItem = (DiskFileItem)multipartFile.getFileItem();
		if (diskFileItem.isInMemory()){
			DeferredFileOutputStream deferredFileOutputStream = (DeferredFileOutputStream)diskFileItem.getOutputStream();
			byte[] byteArr = deferredFileOutputStream.getData();
			ByteArrayBody byteArrayBody = new ByteArrayBody(byteArr,file.getOriginalFilename());
			entity.addPart("file", byteArrayBody);
		}else{
			File localfile = diskFileItem.getStoreLocation();
			FileBody fileBody = new FileBody(localfile);
			entity.addPart("file", fileBody);
		}
        entity.addPart("projectCode", new StringBody(projectCode, ContentType.create("text/plain", Consts.UTF_8)));
        entity.addPart("enterPoint", new StringBody(deployment.getEnterPoints(), ContentType.create("text/plain", Consts.UTF_8)));
        
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity.build());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpPost);
       
        int state = response.getStatusLine().getStatusCode();
        if (state != HttpStatus.SC_OK) {
        	throw new BizException("falut", "请求返回:"+state+"("+url+")");
		}else{
        	HttpEntity responseEntity = response.getEntity();
        	String jsonString = EntityUtils.toString(responseEntity);
        	JSONObject json = JSON.parseObject(jsonString);
        	if("success".equals(json.getString("code"))) {
	        	deployment.setFileName(json.getString("fileName"));
				deployment.setUploadStatus(DeployStatus.UPLOAD_NOT_CONNECT);
				this.ruleDeployOnlineService.save(deployment);
        	}else {
        		throw new BizException("falut", json.getString("msg"));
        	}
		}
        
    }
    
    /**
     * 上传数据到服务器
     * @param file
     * @param res
     * @param projectCode
     * @param id
     * @throws Exception
     */
    @RequestMapping("setDataSql")
    public void setDataSql(String id,String projectCode, String modelName,String fileOrSql,String sparkSql) throws Exception {
        if(StringUtils.isEmpty(projectCode)) {
        	projectCode = this.getCurrProjectCode();
        }
    	RuleDeployment deployment = this.ruleDeployOnlineService.deployRemoteServer(id, projectCode);
    	deployment.setFileOrSql(fileOrSql);
    	deployment.setDataSql(sparkSql);
    	
    	String url = deployment.getServerUrl()+Global.getConfig("RuleSparkSQL");

		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		
    	List<NameValuePair> list = new ArrayList<NameValuePair>();
		BasicNameValuePair basicNameValuePair = new BasicNameValuePair("projectCode", projectCode);
		BasicNameValuePair basicNameValuePair2 = new BasicNameValuePair("enterPoint", deployment.getEnterPoints());
		BasicNameValuePair basicNameValuePair3 = new BasicNameValuePair("dataSql", deployment.getDataSql());
		list.add(basicNameValuePair);
		list.add(basicNameValuePair2);
		list.add(basicNameValuePair3);
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
		httpPost.setEntity(formEntity);

		this.ruleDeployOnlineService.save(deployment);
		HttpResponse response = httpClient.execute(httpPost);
		int state = response.getStatusLine().getStatusCode();
        if (state != HttpStatus.SC_OK) {
        	throw new RuntimeException("请求返回:"+state+"("+url+")");
		}else{
			deployment.setUploadStatus(DeployStatus.SQL_NOT_CONNECT);
			this.ruleDeployOnlineService.save(deployment);
		}
        
    }
    
    
    /**
     * 设置数据关联
     * @param file
     * @param res
     * @param projectCode
     * @param id
     * @throws Exception
     */
    @RequestMapping("setReflactData")
    public @ResponseBody ResMessage setReflactData(String reflactDataVOStr, HttpServletResponse res) throws Exception {
    	reflactDataVOStr = reflactDataVOStr.replace("&quot;", "\"");
    	ReflactDataVO reflactDataVO = JSON.parseObject(reflactDataVOStr,ReflactDataVO.class);
    	RuleDeployment deployment = this.ruleDeployOnlineService.deployRemoteServer(reflactDataVO.getDeploymentId(), this.getCurrProjectCode());
    	this.reflactDataService.insertOrUpdate(reflactDataVO,deployment);
    	try {
    	int state = this.ruleDeployOnlineService.setReflactData(deployment, reflactDataVO);
    	
        if (state != HttpStatus.SC_OK) {
        	return new ResMessage("falut", "请求返回:"+state);
		}else{
			deployment.setUploadStatus(DeployStatus.UPLOAD_CONNECT);
			this.ruleDeployOnlineService.save(deployment);
			return new ResMessage("success", "数据关联设置成功！");
		}
    	}catch(org.apache.http.conn.HttpHostConnectException e) {
    		return new ResMessage("falut", "映射数据保存成功！但部署失败，"+e);
    	}catch(org.apache.http.client.ClientProtocolException e) {
    		return new ResMessage("falut", "映射数据保存成功！但部署失败，部署url配置错误！"+e);
    	}
    }
    /**
     * 获取部署项目
     *
     * @param request HttpServletRequest
     * @param id    部署任务的id
     * @return 部署结果信息
     */
    @RequestMapping("getRuleDeployment")
    public @ResponseBody JSONObject getRuleDeployment(HttpServletRequest request, String id) throws Exception {
		RuleDeployment deployment = this.ruleDeployOnlineService.deployRemoteServer(id, this.getCurrProjectCode());
		return (JSONObject)JSON.toJSON(deployment);
    }
	
    /**
     * 获取数据关联
     * @param file
     * @param res
     * @param projectCode
     * @param id
     * @throws Exception
     */
    @RequestMapping("getReflactData")
    public @ResponseBody JSONObject getReflactData(String projectCode, String id,String reflactType, HttpServletResponse res) throws Exception {
    	if(!StringUtils.isNotEmpty(projectCode)) {
    		projectCode = this.getCurrProjectCode();
    	}
    	RuleDeployment deployment = this.ruleDeployOnlineService.deployRemoteServer(id,projectCode);
    	 
    	ReflactData reflactData = new ReflactData();
    	reflactData.setDeployId(deployment.getId());
    	reflactData.setProjectCode(deployment.getProjectCode());
    	List<ReflactData> reflactDataList = this.reflactDataService.findList(reflactData);
    	
    	ReflactDataVO reflactDataVO = new ReflactDataVO();
    	reflactDataVO.setReflactDataList(reflactDataList);
    	reflactDataVO.setDeploymentId(deployment.getId());
    	reflactDataVO.setProjectCode(deployment.getProjectCode());
    	
    	return (JSONObject)JSON.toJSON(reflactDataVO);
    	
    }
    
    
    /**
     * 删除数据关联
     * @param reflactData
     * @param res
     */
    @RequestMapping("delReflactData")
    public @ResponseBody ResMessage delReflactData(ReflactData reflactData, HttpServletResponse res) throws Exception {
    	this.reflactDataService.delete(reflactData);
		return new ResMessage("success", "数据关联删除成功！");
    }
    
    /**
     * 启动spark计算
     * @param file
     * @param res
     * @param projectCode
     * @param id
     * @throws Exception
     */
    @RequestMapping("calc")
    public @ResponseBody ResMessage calc(String projectCode, String id,String enterPoint) throws Exception {
        // MultipartFile对象转换
    	if(!StringUtils.isNotBlank(projectCode)){
    		projectCode = this.getCurrProjectCode();
    	}
    	RuleDeployment deployment = this.ruleDeployOnlineService.deployRemoteServer(id, projectCode);
    	String url = deployment.getServerUrl()+Global.getConfig("RuleSparkStomCalc");

		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		
    	List<NameValuePair> list = new ArrayList<NameValuePair>();
		BasicNameValuePair basicNameValuePair = new BasicNameValuePair("projectCode", projectCode);
		BasicNameValuePair basicNameValuePair2 = new BasicNameValuePair("enterPoint", enterPoint);
		list.add(basicNameValuePair);
		list.add(basicNameValuePair2);
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
		httpPost.setEntity(formEntity);
		try {
			HttpResponse response = httpClient.execute(httpPost);
			int state = response.getStatusLine().getStatusCode();
	        if (state != HttpStatus.SC_OK) {
	        	return new ResMessage("error", "请求返回:"+state+"("+url+")");
			}else {
				HttpEntity entitys = response.getEntity();  
				if (entitys != null) {  
					String result=EntityUtils.toString(entitys);
					JSONObject obj = JSON.parseObject(result);
					if("error".equals(obj.getString("code"))){
						return new ResMessage("error", obj.getString("msg"));
					}else {
						return new ResMessage("success", "spark 计算完成！"); 
					}
				}else {
					return new ResMessage("error", "spark 计算异常！");
				}
				
			}
		}catch(HttpHostConnectException e) {
			return new ResMessage("error", "服务端执行器未启动"); 
		}
    }
    /**
     * 下载计算结果
     * @param uploadType
     * @param request
     * @param res
     * @param projectCode
     * @param id
     * @throws Exception
     */
    @RequestMapping("/download{uploadType:.*}")
    public void handle(@PathVariable String uploadType, HttpServletRequest request, HttpServletResponse res, String projectCode, String id) throws Exception {
        if (StringUtils.isBlank(projectCode)) {
            projectCode = (String) request.getSession().getAttribute("CURRPROJECTCODE");
        }
        RuleDeployment deployment = this.ruleDeployOnlineService.deployRemoteServer(id, this.getCurrProjectCode());
        String enterPoint = deployment.getEnterPoints();
        String url = deployment.getServerUrl()+Global.getConfig("RuleDataDownload");
        
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost   

    	List<NameValuePair> list = new ArrayList<NameValuePair>();
		BasicNameValuePair basicNameValuePair = new BasicNameValuePair("projectCode", projectCode);
		BasicNameValuePair basicNameValuePair2 = new BasicNameValuePair("enterPoint", enterPoint);
		list.add(basicNameValuePair);
		list.add(basicNameValuePair2);
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
		httpPost.setEntity(formEntity);
		
		HttpResponse response = httpClient.execute(httpPost);
		String filename = getFileName(response);
		HttpEntity entity = response.getEntity();
		InputStream in = entity.getContent();

        OutputStream os = res.getOutputStream();
        res.reset();
        res.setContentType("application/octet-stream; charset=utf-8");
        
        res.setHeader("Content-Disposition", "attachment; filename=" + filename);
        try {
        	byte[] buf = new byte[1024];
         	int len = in.read(buf);
         	while(len != -1) {
         		os.write(buf,0,len);
         		len = in.read(buf);
         	}
            os.flush();
        } catch (Exception e) {
            LoggerManager.error("", e, this.getClass());
        } finally {
        	if (in != null) {
                in.close();
            }
            if (os != null) {
                os.close();
            }
        }
        
    }
    
    /** 
     * 获取response header中Content-Disposition中的filename值 
     * @param response 
     * @return 
     */  
    public String getFileName(HttpResponse response) {
        Header contentHeader = response.getFirstHeader("Content-Disposition");  
        String filename = null;  
        if (contentHeader != null) {  
            HeaderElement[] values = contentHeader.getElements();
            
            if (values.length == 1) {  
                NameValuePair param = values[0].getParameterByName("filename");  
                if (param != null) {  
                    try {  
                        filename = param.getValue();  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
        return filename;  
    }  
    @RequestMapping("downLoadSqlScript")
    public void downLoadSqlScript( @RequestParam("id") String id,@RequestParam("projectCode") String  projectCode,HttpServletResponse response) throws Exception {
        RuleDataInfo ruleDataInfo = this.ruleDeployOnlineService.getRulePackageData(projectCode,id);
        OutputStream os = response.getOutputStream();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddhhMMss");
            response.setHeader("Content-Disposition", "attachment; filename=deployrulescript"+sdf.format(new Date())+".sql");
            response.setContentType("application/octet-stream; charset=utf-8");
            os.write(JSON.toJSONString(ruleDataInfo).getBytes());
//            os.write(ruleDataInfo.getDeploySql().getBytes());
            os.flush();
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }
    @RequestMapping("getDataComponent")
    public @ResponseBody
    JsonMessage getDataComponent() throws Exception {
        JsonMessage ret = new JsonMessage();
        try {
            List<RuleDatacomponent> dcList = dataComponentService.findPublishList(this.getCurrProjectCode());
            ret.setData((Serializable) dcList);
        } catch (Exception e) {
            ret.setMessage(e.getMessage());
            ret.setResult(false);
        }
        return ret;
    }

    //工作流------------------------
    @Autowired(required = false)
    private IWorkflowService workflowService;

    @RequestMapping("processList")
    @ResponseBody
    public ProcessBean getProcessList(){
        ProcessBean ret = null;
        try {
            ProcessInfo info = new ProcessInfo();
            info.setPageSize(String.valueOf(Integer.MAX_VALUE));
            ret = workflowService.processDefinitionList(info);
        } catch (Exception e) {
            logger.error("获取流程列表失败："+e.getMessage(),e);
            ret = new ProcessBean();
            ret.setRetMsg(e.getMessage());;

        }
        return ret;
    }

    /**
     * 规则部署审批页面
     * @param map
     * @param id 联机部署ID
     * @return
     * @throws Exception
     */
    @RequestMapping("deployCheck")
    public String deployCheck(ModelMap map, String id) throws Exception {

        RuleDeployVO ruleDeployVO =  this.ruleDeployOnlineService.findRuleDeploy(id);

        RuleVersioninfo info = new RuleVersioninfo();
        info.setProjectCode(ruleDeployVO.getRuleDeployment().getProjectCode());
        info.setModelType(RuleModelTypeEnum.RuleFlow.code);
        List<SelectEditorVo> list = this.ruleFlowService.getAllPublishVersion(info);

        map.put("list", list);

        map.put("vo", ruleDeployVO);
        return "rule/deployonline/deployCheck";
    }

    @RequestMapping("agreeDeploy")
    @ResponseBody
    public ResMessage agreeDeploy(@RequestParam String processInstanceId,@RequestParam String id,
                                  @RequestParam String taskId,@RequestParam String projectCode,String opinion){
        ResMessage res = new ResMessage();

        try {
            TaskBean task = new TaskBean();
            task.setTaskId(taskId);
            task.setUserId(this.getCurrUser().getId());
            task.setVotingOpinion(opinion);
            TaskBean result = this.workflowService.submitTask(task);
            if("1".equals(result.getRetCode())){//任务提交失败
                res.setCode("fail");
                res.setMsg(result.getRetMsg());
                return res;
            }
            res.setMsg(result.getRetMsg());
            result = this.workflowService.getTasksByProcessInstanceId(processInstanceId);
            if("Y".equals(result.getIsFinished())&&"agree".equals(opinion)){//审批完成,执行规则部署动作
            	RuleDeployment  ruleDeploy  = new RuleDeployment();
            	ruleDeploy.setId(id);
            	ruleDeploy.setProjectCode(projectCode);
            	ResponseVO responseVO = this.doDeploy(null, ruleDeploy);
            	if(responseVO.getStatus() == ResponseVO.OK) {
            		res.setCode("success");
            		res.setMsg((String)responseVO.getData());
            	}else{
            		res.setCode("fail");
            		res.setMsg((String)responseVO.getDescription());
            	}
                return res;
            }else if("N".equals(result.getIsFinished())&&"against".equals(opinion)){
                ProcessInfo info = new ProcessInfo();
                info.setProcessInstanceId(processInstanceId);
                ProcessBean processBean = this.workflowService.terminateProcess(info);
                res.setMsg(processBean.getRetMsg());
                if("1".equals(processBean.getRetCode())){
                    res.setCode("fail");
                }
            }
        } catch (Exception e) {
            logger.error("审批失败", e);
            res.setCode("fail");
            res.setMsg(e.getMessage());
        }
        return res;

    }

    /**
     * 执行部署任务前，判断该部署信息是否已审批 ljt
     * @param id
     * @return
     */
    @RequestMapping("isStatusInd")
    public  ResponseVO isStatusInd(@RequestBody RuleDeployment ruleDeploy) {
        ResponseVO responseVO = new ResponseVO();
        try {
            responseVO.setStatus(200);
            RuleDeployment deployment = ruleDeployOnlineService.get(ruleDeploy.getId());
            String statusInd = deployment.getStatusInd();
            if(!("1".equals(statusInd)||"2".equals(statusInd))){
                responseVO.setStatus(500);
            }
        } catch (Exception e) {
            responseVO.setStatus(500);
            e.printStackTrace();
        }
        return responseVO;
    }
}
